package com.zeny.express.framework.mq.activemq;

import org.apache.activemq.ActiveMQConnection;
import org.apache.commons.pool.BasePoolableObjectFactory;
import org.apache.commons.pool.impl.GenericObjectPool.Config;

import com.ibm.mq.MQQueue;
import com.zeny.express.framework.mq.AbstractMqPool;

/**
 * refer to : redis.clients.jedis.JedisPool
 */
public class ActiveMqPool extends AbstractMqPool {
	private String brokerURL;
	private String queueName;
	
	public ActiveMqPool(Config poolConfig, String brokerURL, String queueName)
	{
		this(poolConfig, ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, brokerURL, queueName);
	}
	
    public ActiveMqPool( Config poolConfig, String userName, String password, String brokerURL,
                     String queueName) {
        super(poolConfig, new MqFactory(userName, password, brokerURL, queueName));
        
        this.brokerURL = brokerURL;
        this.queueName = queueName;
    }

	public void returnBrokenResource(final MQQueue resource) {
    	returnBrokenResourceObject(resource);
    }
    
    public void returnResource(final MQQueue resource) {
    	returnResourceObject(resource);
    }
    
    private static class MqFactory extends BasePoolableObjectFactory {

    	private String userName;
    	private String password;
    	private String brokerURL;
    	private String queueName;

        public MqFactory( String userName, String password, String brokerURL,
                String queueName) {
            super();

            this.userName = userName;
            this.password = password;
            this.brokerURL = brokerURL;
            this.queueName = queueName;
        }

        public Object makeObject() throws Exception {
        	ActiveMqQueueHandler handler = new ActiveMqQueueHandler(userName, password, brokerURL, queueName);
        	handler.make();
            
            return handler;
        }

        public void destroyObject(final Object obj) throws Exception {
            if (obj instanceof ActiveMqQueueHandler) {
                final ActiveMqQueueHandler handler = (ActiveMqQueueHandler) obj;

                handler.close();
            }
        }

        //TODO:队列状态校验
//        public boolean validateObject(final Object obj) {
//            
//        }
    }
}
